# -*- coding: utf-8 -*-
"""
订单状态管理控制器

处理订单状态查询、更新和管理相关的HTTP请求
"""
from fastapi import APIRouter, HTTPException, Depends, Query
from pydantic import BaseModel
from typing import Optional
from app.controllers.user_controller import get_current_user
from app.services.order_status_service import OrderStatusService

# 创建状态管理路由
status_router = APIRouter(
    prefix="/order-status",
    tags=["order-status"],
    responses={404: {"description": "Not found"}}
)

# 创建UniApp兼容路由
uniapp_status_router = APIRouter(
    prefix="/uniapp/order-status",
    tags=["uniapp-order-status"],
    responses={404: {"description": "Not found"}}
)

# 初始化服务
order_status_service = OrderStatusService()


# ==================== 请求模型 ====================

class StatusUpdateRequest(BaseModel):
    new_status: str
    notes: Optional[str] = None


# ==================== 标准API接口 ====================

@status_router.get("/{order_id}")
async def get_order_status(
    order_id: str,
    current_user = Depends(get_current_user)
):
    """获取订单状态信息"""
    try:
        user_id = current_user.get('user_id')
        result = order_status_service.get_order_status_info(order_id, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单状态失败: {str(e)}")


@status_router.put("/{order_id}")
async def update_order_status(
    order_id: str,
    request: StatusUpdateRequest,
    current_user = Depends(get_current_user)
):
    """更新订单状态"""
    try:
        user_id = current_user.get('user_id')
        result = order_status_service.update_order_status(
            order_id, 
            request.new_status, 
            user_id, 
            request.notes,
            "user"
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新订单状态失败: {str(e)}")


@status_router.get("/list/by-status")
async def get_orders_by_status(
    status: str = Query(..., description="订单状态"),
    limit: int = Query(20, ge=1, le=100, description="返回数量"),
    offset: int = Query(0, ge=0, description="偏移量"),
    current_user = Depends(get_current_user)
):
    """根据状态获取订单列表"""
    try:
        user_id = current_user.get('user_id')
        result = order_status_service.get_orders_by_status(status, user_id, limit, offset)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单列表失败: {str(e)}")


@status_router.get("/statistics")
async def get_status_statistics(current_user = Depends(get_current_user)):
    """获取订单状态统计"""
    try:
        user_id = current_user.get('user_id')
        result = order_status_service.get_status_statistics(user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取状态统计失败: {str(e)}")


# ==================== UniApp兼容接口 ====================

@uniapp_status_router.get("/{order_id}")
async def uniapp_get_order_status(
    order_id: str,
    current_user = Depends(get_current_user)
):
    """UniApp获取订单状态信息"""
    try:
        user_id = current_user.get('user_id')
        result = order_status_service.get_order_status_info(order_id, user_id)
        
        if result['success']:
            data = result['data']
            return {
                "code": 200,
                "message": "获取成功",
                "data": {
                    "order_id": order_id,
                    "current_status": data['current_status'],
                    "payment_status": data['payment_status'],
                    "payment_type": data['payment_type'],
                    "next_actions": data['possible_next_statuses'],
                    "status_history": data['status_history'][:5],  # 只返回最近5条历史
                    "updated_time": data['updated_time']
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单状态失败: {str(e)}")


@uniapp_status_router.get("/list/by-status")
async def uniapp_get_orders_by_status(
    status: str = Query(..., description="订单状态"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=50, description="每页数量"),
    current_user = Depends(get_current_user)
):
    """UniApp根据状态获取订单列表"""
    try:
        user_id = current_user.get('user_id')
        offset = (page - 1) * page_size
        result = order_status_service.get_orders_by_status(status, user_id, page_size, offset)
        
        if result['success']:
            data = result['data']
            total_pages = (data['total'] + page_size - 1) // page_size
            
            return {
                "code": 200,
                "message": "获取成功",
                "data": {
                    "orders": data['orders'],
                    "pagination": {
                        "page": page,
                        "page_size": page_size,
                        "total": data['total'],
                        "total_pages": total_pages,
                        "has_next": page < total_pages,
                        "has_prev": page > 1
                    },
                    "status_filter": status
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单列表失败: {str(e)}")


@uniapp_status_router.get("/statistics/summary")
async def uniapp_get_status_summary(current_user = Depends(get_current_user)):
    """UniApp获取订单状态统计摘要"""
    try:
        user_id = current_user.get('user_id')
        result = order_status_service.get_status_statistics(user_id)
        
        if result['success']:
            data = result['data']
            
            # 格式化为前端友好的格式
            summary = {
                "total_orders": data['total_orders'],
                "total_amount": data['total_amount'],
                "status_counts": {}
            }
            
            # 重点关注的状态
            key_statuses = ['submitted', 'paid', 'shipped', 'delivered', 'completed']
            
            for stat in data['statistics']:
                status = stat['status']
                if status in key_statuses:
                    summary['status_counts'][status] = {
                        "count": stat['count'],
                        "amount": stat['total_amount'],
                        "info": stat['status_info']
                    }
            
            return {
                "code": 200,
                "message": "获取成功",
                "data": summary
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取状态统计失败: {str(e)}")


@uniapp_status_router.get("/flow/definition")
async def uniapp_get_status_flow():
    """UniApp获取订单状态流程定义"""
    try:
        from app.models.order_status import OrderStatusTransition, OrderStatusDisplay, PaymentType
        
        # 返回状态流程定义
        flow_data = {
            "online_payment_flow": [
                {
                    "status": status.value,
                    "info": OrderStatusDisplay.get_status_info(status)
                } for status in OrderStatusTransition.ONLINE_PAYMENT_FLOW
            ],
            "offline_payment_flow": [
                {
                    "status": status.value,
                    "info": OrderStatusDisplay.get_status_info(status)
                } for status in OrderStatusTransition.OFFLINE_PAYMENT_FLOW
            ]
        }
        
        return {
            "code": 200,
            "message": "获取成功",
            "data": flow_data
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取状态流程失败: {str(e)}")


# ==================== 管理员接口 ====================

@status_router.put("/admin/{order_id}")
async def admin_update_order_status(
    order_id: str,
    request: StatusUpdateRequest,
    current_user = Depends(get_current_user)
):
    """管理员更新订单状态"""
    try:
        # TODO: 添加管理员权限检查
        admin_id = current_user.get('user_id')
        
        result = order_status_service.update_order_status(
            order_id, 
            request.new_status, 
            admin_id, 
            request.notes,
            "admin"
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"管理员更新订单状态失败: {str(e)}")


@status_router.get("/admin/statistics")
async def admin_get_all_status_statistics():
    """管理员获取全部订单状态统计"""
    try:
        result = order_status_service.get_status_statistics()  # 不传user_id获取全部
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取全部状态统计失败: {str(e)}") 